<script setup lang="ts">
import { useLayoutConfigStore } from '@/store/layoutConfig'
import type { RouteLocationNormalized, RouteRecordNormalized } from 'vue-router'

/**
 * 第一次加载触发
 */
const route = useRoute()
const router = useRouter()
onMounted(() => {
  getBreadcrumb(route)
})

/**
 * 路由更新时会触发
 */
onBeforeRouteUpdate((to) => {
  getBreadcrumb(to)
})

/**
 * 获取当前路由的面包屑
 * @param to 目标路由对象 
 */
const breadcrumbList = ref<RouteRecordNormalized[]>([])
function getBreadcrumb(to: RouteLocationNormalized) {
  // console.log('getBreadcrumb', to.matched);
  const matched = to.matched.filter(item => item.meta && item.meta.title && item.meta.isBreadcrumd)
  // console.log('getBreadcrumb', matched);
  breadcrumbList.value = matched
  // console.log('breadcrumbList.value0', breadcrumbList.value);
}

/**
 * 展开/折叠
 */
const layoutConfigStore = useLayoutConfigStore()
const { isCollapse } = storeToRefs(layoutConfigStore)
function handleChangeCollapse() {
  isCollapse.value = !isCollapse.value
}

/**
 * 点击标题路由跳转
 */
function handleLink(_route: RouteRecordNormalized) {
  const { redirect, path } = _route
  console.log(redirect, path);
  if (redirect) {
    router.push(redirect as string)
  } else {
    router.push(path)
  }
}

</script>

<template>
  <div class="h-60px flex items-center justify-around">
    <!-- 收缩图标 -->
    <div class="hover:bg-#f1f1f1 cursor-pointer p-8px rounded-6px flex items-center justify-center text-[#595b5c]"
      @click="handleChangeCollapse">
      <SvgIcon width="17" height="17" :name="isCollapse ? 'expand' : 'fold'" />
    </div>
    <div class="ml-10px">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="(item, index) in breadcrumbList" :key="item.path">
          <span v-if="index === breadcrumbList.length - 1" class="flex items-center justify-center">
            <SvgIcon v-if="item.meta.icon" width="17" height="17" :name="item.meta?.icon" />
            <span class="ml-5px">{{ item.meta.title }}</span>
          </span>
          <a v-else @click.prevent="handleLink(item)" class="flex items-center justify-center">
            <SvgIcon v-if="item.meta.icon" width="17" height="17" :name="item.meta?.icon" class="text-[#3f4142]" />
            <span class="ml-5px text-[#3f4142]">{{ item.meta.title }}</span>
          </a>
        </el-breadcrumb-item>
      </el-breadcrumb>
    </div>
  </div>
</template>

<style scoped lang="scss"></style>